local base = _G
module("gui")

LabelG = {}
LabelGMT = { __index = LabelG }

base.setmetatable(LabelG, { __index = ObjectG })

LabelG.create = function(x, y, text, width ,height)
  local styles = get_styles('font', 'align', 'drop_shadow_offset')
  local colors = get_colors('font', 'drop_shadow')
  width = width or styles.font:get_width(text)
  height = height or styles.font:get_height()

  local self = Object(x, y, width, height, LabelGMT)

  self.styles = styles
  self.colors = colors
  
  self.text = text
  self.is_down = false

  return self
end

LabelG.destroy = function(self)
  self.text = nil
  self.is_down = nil
  
  self.styles = nil
  self.colors = nil
  ObjectG.destroy(self)
end

-- handle mouse input
LabelG.mouse_press = function(self, button, x, y)
  self.is_down = true
  self:on_select()
end

LabelG.mouse_release = function(self, button, x, y)
  self.is_down = false
end

LabelG.redraw = function(self, delta)
  local c = self.node.canvas
  c:clear()

  local alpha = 0.8
  if self.is_down == true and self.is_hovered == true then
    alpha = 1
  elseif self.is_hovered == true then
    alpha = 0.9
  end

  -- write the text
  local out = self.text
  if out == nil then
    return
  end
  out = self.styles.font:clamp(out, self.width, "...")
  -- text alignment
  local w = self.styles.font:get_width(out)
  local x = 0
  if self.styles.align == 'center' then
    x = self.width/2 - w/2
  elseif self.styles.align == 'right' then
    x = self.width - w
  end
  local ds = self.colors.drop_shadow
  local dso = self.styles.drop_shadow_offset
  if ds and dso then
    c:move_to(x, -self.height + dso)
    c:set_font(self.styles.font, ds, alpha)
    c:write(out)
  end
  c:move_to(x, -self.height)
  c:set_font(self.styles.font, self.colors.font, alpha)
  c:write(out)

  --[[
  -- WIP ahead
  local styles = self.styles
  local colors = self.colors
  if colors.drop_shadow and styles.drop_shadow_offset then
    c:set_font(self.styles.font, colors.drop_shadow, alpha)
    c:write_clamp(styles.font, self.text, 0, -self.height + styles.drop_shadow_offset, self.width, styles.align)
  end
  c:set_font(styles.font, colors.font, alpha)
  c:write_clamp(styles.font, self.text, 0, -self.height, self.width, styles.align)
  ]]
end

LabelG.update = function(self, dt)
  -- todo: don't redraw all the time
  self:redraw()
end

-- events
LabelG.on_select = function(self)

end

Label = LabelG.create